﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MensUnoShop.Models;
using SenerPro;

namespace MensUnoShop.Filters
{
    /// <summary>
    /// 過濾賣場相關屬性，並建立賣場及當下類別物件
    /// </summary>
    public class NormalMarketFilter : ActionFilterAttribute
    {
        private Logger _log;

        public NormalMarketFilter()
        {
            _log = new Logger(Config.logpath);
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            NormalMarket mk = null;
            Guid mkguid;
            int tid = 0;
            int.TryParse(filterContext.ActionParameters["tagid"] == null ? "" : filterContext.ActionParameters["tagid"].ToString(), out tid);
            List<Tag> navlist = new List<Tag>();
            string mksn = filterContext.ActionParameters["mksn"] as string;
            string pdtag = filterContext.ActionParameters["pdtag"] as string;
            //建立賣場物件
            mk = MarketFactory.GetNormalMarket(mksn);
            if (mk != null)
            {
                if (mk.TAGID != tid || !mk.PRODUCTLIST.Exists(p => p.TITLETAGID == int.Parse(pdtag)))
                {
                    _log.RecordException(_log.FlowLogPath, mk.SN+";"+string.Join(",",mk.PRODUCTLIST.Select(p=>p.TITLETAGID).ToArray()));
                    filterContext.Result = new RedirectResult("/market/n/" + mk.SN + "/" + mk.PRODUCTLIST.First().TITLETAGID + "/" + mk.TAGID);
                }
                else
                {
                    filterContext.Controller.ViewData["market"] = mk;

                    Tag tag = TagFactory.GetTag(mk.TAGID);
                    if (tag != null)
                    {
                        navlist = TagFactory.GetNavTagList(mk.TAGID);
                        filterContext.Controller.ViewData["navlist"] = navlist;
                        filterContext.Controller.ViewData["currenttag"] = tag;
                    }
                    else
                    {
                        _log.RecordException(_log.FlowLogPath, "tag is not correct");
                        filterContext.Result = new RedirectResult("/");
                    }

                }
            }
            else
            {
                _log.RecordException(_log.FlowLogPath, "market is not correct");
                filterContext.Result = new RedirectResult("/");
            }





            base.OnActionExecuting(filterContext);
        }
    }
    
    

   

}